package com.itheima.reggie.service.Impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private CartService cartService;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderService orderService;
    //前端添加提交订单
    @Override
    public void save(Order order) {
        //获取当前用户
        User user = UserHolder.get();
        //调用findAll查询方法查询购物车
        List<Cart> cartList = cartService.findAll();
        if (CollectionUtil.isEmpty(cartList)){
            throw new CustomException("购物车为空");
        }
        //根据addressid查询用户的其他地址信息
        Address address = addressMapper.selectById(order.getAddressId());
        if (address==null){
            throw new CustomException("没有收货地址,无法下单");
        }
       //组装订单详情数据,保存订单详情表
        //先装订多表 定义主键
        Long orderId= IdWorker.getId();
        //添加一个购物项 并保存到订单表中
        BigDecimal amount = new BigDecimal(0);//初始化金额为0 ======> int amount = 0
        for (Cart cart : cartList) {
            OrderDetail orderDetail = new OrderDetail();//订单详情
            orderDetail.setName(cart.getName());//购物车中菜品名称
            orderDetail.setOrderId(orderId);//提前生成
            orderDetail.setDishId(cart.getDishId());//菜品id
            orderDetail.setSetmealId(cart.getSetmealId());//套餐id
            orderDetail.setDishFlavor(cart.getDishFlavor());//菜品口味
            orderDetail.setNumber(cart.getNumber());//菜品数量
            orderDetail.setAmount(cart.getAmount());//金额
            orderDetail.setImage(cart.getImage());//图片

            //叠加金额  amount = amount + cart.getAmount() * cart.getNumber()
            amount = amount.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));

            orderDetailMapper.insert(orderDetail);
        }
        //组装订单数据,保存订单表
        order.setId(orderId);//这个订单的主键是我们自己定义的
        order.setNumber(String.valueOf(orderId));//订单号 自己定义
        order.setStatus(1);//1 表示待付款
        order.setUserId(user.getId());//下单用户id
        order.setOrderTime(new Date());//下单时间
        order.setCheckoutTime(new Date());//todo 支付时间,应该是支付的时候才来填这个值
        order.setAmount(amount);//订单总金额 = 所有订单项金额之和
        order.setUserName(user.getName());
        order.setPhone(address.getPhone());//地址中得联系电话
        StringBuilder sb = new StringBuilder();//拼接具体地址
        sb.append(StringUtils.isNotEmpty(address.getProvinceName()) ? address.getProvinceName() : "");
        sb.append(StringUtils.isNotEmpty(address.getCityName()) ? address.getCityName() : "");
        sb.append(StringUtils.isNotEmpty(address.getDistrictName()) ? address.getDistrictName() : "");
        sb.append(StringUtils.isNotEmpty(address.getDetail()) ? address.getDetail() : "");
        order.setAddress(sb.toString());//联系地址
        order.setConsignee(address.getConsignee());//地址中取得的联系人名称
        orderMapper.insert(order);
        //清理购物车
        cartService.delete();
    }
    //后端分页查询订单信息
    @Override
    public Page<Order> getOrderList(String number, Integer pageNum, Integer pageSize, Date beginTime,Date endTime) {
        //定义查询条件
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(null),Order::getNumber,number);
        wrapper.ge(StringUtils.isNotEmpty(null),Order::getOrderTime,beginTime).le(StringUtils.isNotEmpty(null),Order::getCheckoutTime,endTime);
        //创建分页查询
        Page<Order> page = new Page<>(pageNum,pageSize);
        page=orderMapper.selectPage(page,wrapper);

        return page;
    }
    //分页查询历史订单
    @Override
    public Page getUserPage(Integer pageNum, Integer pageSize) {
        //分页查询我的订单
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId,UserHolder.get().getId());
        //根据时间填入倒叙显示最新订单
        wrapper.orderByDesc(Order::getOrderTime);
        Page<Order> page = new Page<>(pageNum, pageSize);
        page=orderMapper.selectPage(page,wrapper);
        //遍历我的订单
        List<Order> records = page.getRecords();
        if (CollectionUtil.isNotEmpty(records)){
            for (Order record : records) {
                //根据id添加订单详细
                LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(OrderDetail::getOrderId,record.getId());
                List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper1);
                //将得到的订单详情存入到订单中
                record.setOrderDetails(orderDetailList);
            }
        }
        return page;
    }


}
